import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const serviceFlow = axios.create({
  baseURL: process.env.VUE_APP_BASE_API_PAY, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
serviceFlow.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // 请求头 设置token
      config.headers['authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
serviceFlow.interceptors.response.use(
  response => {
    const res = response.data
    // 如果返回的状态码不是200，则判断为错误
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 常见特殊响应码判断
      if (res.code === 501) {
        MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      // 登录成功提示
      if (res.msg === '登录成功！') {
        Message({
          message: res.msg,
          type: 'success',
          duration: 5 * 1000
        })
      }
      // 退出登录成功提示
      if (res.msg === '退出登录成功！') {
        Message({
          message: res.msg,
          type: 'success',
          duration: 5 * 1000
        })
      }
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default serviceFlow
